package com.xunqi.pay.controller;

import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayResponse;
import com.xunqi.pay.pojo.PayInfo;
import com.xunqi.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-05-11 18:17
 **/

@Slf4j
@Controller
@RequestMapping(value = "/pay")
public class PayController {

    @Resource
    private PayService payService;

    @Resource
    private WxPayConfig wxPayConfig;

    @GetMapping(value = "/create")
    public ModelAndView create(@RequestParam("orderId")String orderId,
                               @RequestParam("amount") BigDecimal amount,
                               @RequestParam("payType")BestPayTypeEnum bestPayTypeEnum) {

        PayResponse payResponse = payService.create(orderId, amount,bestPayTypeEnum);

        Map<String,String> map = new HashMap<String, String>();

        //支付方式不同，渲染也不同,WXPAY_NATIVE使用codeUrl，ALIPAY_PC使用body
        //使用微信Native支付
        if (bestPayTypeEnum == BestPayTypeEnum.WXPAY_NATIVE) {
            //传入前台的二维码路径生成支付二维码
            map.put("codeUrl",payResponse.getCodeUrl());
            map.put("orderId",payResponse.getOrderId());
            map.put("returnUrl",wxPayConfig.getReturnUrl());
            return new ModelAndView("createForWxNative",map);
            //使用支付宝pc支付
        } else if (bestPayTypeEnum == BestPayTypeEnum.ALIPAY_PC) {
            map.put("body",payResponse.getBody());
            return new ModelAndView("createForAlipayPc",map);
        }

        throw new RuntimeException("暂不支持的支付类型");

    }


    @PostMapping(value = "/notify")
    @ResponseBody
    public String asyncNotify(@RequestBody String notifyData) {
        //异步通知结果
        return payService.asyncNotify(notifyData);
    }

    //根据订单号查询订单状态的API
    @GetMapping(value = "/queryByOrderId")
    @ResponseBody
    public PayInfo queryByOrderId(@RequestParam("orderId") String orderId) {
        return payService.queryByOrderId(orderId);
    }

}
